package com.ruoyi.boc.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SendSmsUtils {

    // 定义用于验证中国手机号码的正则表达式
    private static final String PHONE_NUMBER_REGEX = "^1[3-9]\\d{9}$";

    /**
     * 验证手机号码是否符合中国手机号码的格式
     *
     * @param phoneNumber 要验证的手机号码
     * @return 如果手机号码格式正确，则返回true；否则返回false
     */
    public static boolean isValidPhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return false; // 如果输入为空，则认为格式不正确
        }
        return phoneNumber.matches(PHONE_NUMBER_REGEX);
    }

    public static boolean sendSms(String host,int port,String molile, String message) throws Exception {

        String serviceid = "0000";
        String mobilenum = "1";
        String backCode = "0012000000000000";
        message = message.replaceAll("\r", "").replaceAll("\n", "");
        StringBuffer body = new StringBuffer();
        int messsageLength = message.getBytes().length;
        body.append(mobilenum);
        body.append(strLength(messsageLength, 3, "0"));
        body.append(molile);
        body.append(message);
        String msg = new StringBuilder().append(serviceid).append(strLength(body.toString().getBytes().length, 4, "0")).append(body.toString()).toString();
        //调用Socket服务
        String charset = "GBK";
        Socket socket = null;
        OutputStream out = null;
        InputStream in = null;
        StringBuffer result = new StringBuffer();
        try {
            socket = new Socket(host, port);
            socket.setSoTimeout(30000);
            out = socket.getOutputStream();
            out.write(msg.getBytes(charset));
            socket.shutdownOutput();
            in = socket.getInputStream();
            int len;
            byte[] bytes = new byte[1024];
            while((len = in.read(bytes)) != -1){
                result.append(new String(bytes, 0, len, charset));
            }
            System.out.println(result.toString());
            if(result.toString().indexOf(backCode) > -1){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) in.close();
                if (out != null) out.close();
                if (socket != null) socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    private static String strLength(int number, int length, String chars) {
        String temp = new StringBuilder().append(number).append("").toString();
        String value = new StringBuilder().append(number).append("").toString();
        for (int i = 0; i < length - temp.length(); i++) {
            value = new StringBuilder().append(chars).append(value).toString();
        }
        return value;
    }
}
